import { useState } from "react";
import Navbar from "../../compoents/Navbar";
import { useNavigate } from "react-router-dom";
import style from "./index.module.css";
import { DatePicker, Toast } from "antd-mobile";
import { useDispatch } from "react-redux";
import { setArchiveData, addArchiveToList } from "../../store/UseStateList";

function Index() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [birthDate, setBirthDate] = useState<Date | null>(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [gender, setGender] = useState<string>('男');
  const [relationship, setRelationship] = useState<string>('本人');
  const [formData, setFormData] = useState({
    name: '',
    idNumber: '',
    phone: '18332266897'
  });

  const relationships = ['本人', '配偶', '父母', '子女', '亲戚', '朋友', '其他'];

  const onFinish = () => {
    // 校验表单数据
    if (!formData.name.trim()) {
      Toast.show('请输入真实姓名');
      return;
    }
    
    if (!formData.idNumber.trim()) {
      Toast.show('请输入身份证号码');
      return;
    }
    
    if (!birthDate) {
      Toast.show('请选择出生日期');
      return;
    }

    const archiveData = {
      name: formData.name,
      namecode: formData.idNumber,
      birthDate: birthDate.toISOString().split('T')[0],
      set: gender,
      temphone: formData.phone,
      relationship: relationship,
      createTime: new Date().toISOString(),
    };
    localStorage.setItem('archiveData', JSON.stringify(archiveData));
    console.log('表单信息', archiveData);
    
    // 将档案数据保存到Redux store
    dispatch(setArchiveData(archiveData));
    // 同时添加到档案列表中
    dispatch(addArchiveToList(archiveData));
    
    // 显示保存成功提示
    Toast.show('档案保存成功！');
    
    // 延迟跳转到Wenzhen页面，并传递参数显示档案选择界面
    setTimeout(() => {
      navigate('/Wenzhen?showFileSelection=true');
    }, 1000);
  };

  const handleDateChange = (value: Date) => {
    setBirthDate(value);
    setShowDatePicker(false);
  };

  const formatDate = (date: Date | null) => {
    if (!date) return '';
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

  const handleGenderSelect = (selectedGender: string) => {
    setGender(selectedGender);
  };

  const handleRelationshipSelect = (selectedRelationship: string) => {
    setRelationship(selectedRelationship);
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };
  return (
    <div className={style.container}>
      <Navbar title="新建档案" showBack={true} onBack={() => navigate(-1)} />

      {/* 警告横幅 */}
      <div className={style.warningBanner}>
        根据国家有关规定,就诊人在未实名认证状态下,平台将无法提供诊断、药品、挂号等服务,请及时实名认证!
      </div>

      <div className={style.content}>
        <h3 className={style.sectionTitle}>基本信息</h3>

        {/* 与您的关系 */}
        <div className={style.relationshipSection}>
          <div className={style.relationshipLabel}>与您的关系</div>
          <div className={style.relationshipButtons}>
            {relationships.map((rel) => (
              <div
                key={rel}
                className={`${style.relationshipButton} ${relationship === rel ? style.active : ''}`}
                onClick={() => handleRelationshipSelect(rel)}
              >
                {rel}
              </div>
            ))}
          </div>
        </div>

        {/* 表单字段 */}
        <div className={style.formSection}>
          {/* 姓名 */}
          <div className={style.formField}>
            <div className={style.fieldLabel}>
              <span className={style.required}>*</span>姓名
            </div>
            <input
              type="text"
              className={style.fieldInput}
              placeholder="请输入真实姓名"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
            />
          </div>

          {/* 身份证号 */}
          <div className={style.formField}>
            <div className={style.fieldLabel}>
              <span className={style.required}>*</span>身份证号
            </div>
            <input
              type="text"
              className={style.fieldInput}
              placeholder="请输入身份证号码"
              value={formData.idNumber}
              onChange={(e) => handleInputChange('idNumber', e.target.value)}
            />
          </div>

          {/* 出生日期 */}
          <div className={style.formField}>
            <div className={style.fieldLabel}>
              <span className={style.required}>*</span>出生日期
            </div>
            <div 
              className={style.dateInput}
              onClick={() => setShowDatePicker(true)}
            >
              {birthDate ? formatDate(birthDate) : '请选择'}
            </div>
          </div>

          {/* 性别 */}
          <div className={style.formField}>
            <div className={style.fieldLabel}>
              <span className={style.required}>*</span>性别
            </div>
            <div className={style.genderButtons}>
              <div
                className={`${style.genderButton} ${gender === '男' ? style.genderActive : ''}`}
                onClick={() => handleGenderSelect('男')}
              >
                男
              </div>
              <div
                className={`${style.genderButton} ${gender === '女' ? style.genderActive : ''}`}
                onClick={() => handleGenderSelect('女')}
              >
                女
              </div>
            </div>
          </div>

          {/* 联系方式 */}
          <div className={style.formField}>
            <div className={style.fieldLabel}>
              <span className={style.required}>*</span>联系方式
            </div>
            <input
              type="text"
              className={style.fieldInput}
              value={formData.phone}
              onChange={(e) => handleInputChange('phone', e.target.value)}
            />
          </div>
        </div>
      </div>

      {/* 保存按钮 */}
      <div className={style.saveButtonContainer}>
        <button className={style.saveButton} onClick={onFinish}>
          保存
        </button>
      </div>

      {/* 日期选择器 */}
      <DatePicker
        visible={showDatePicker}
        onClose={() => setShowDatePicker(false)}
        onConfirm={handleDateChange}
        title="请选择"
        precision="day"
        min={new Date(1900, 0, 1)}
        max={new Date()}
        value={birthDate}
      />
    </div>
  );
}

export default Index;
